/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.procurement.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.procurement.dao.SupplierOrderDAO;
import com.javaeye.procurement.dto.SupplierOrder;
import com.javaeye.procurement.web.SupplierCondition;
import com.javaeye.common.util.DateUtils;
import com.javaeye.common.util.ListUtil;
import com.javaeye.common.web.PageInfo;

public class SupplierOrderService implements ISupplierOrderService {
	
	private static Log log = LogFactory.getLog(SupplierOrderService.class);
	
	private SupplierOrderDAO dao;
	
	public void setDao(SupplierOrderDAO dao) {
		this.dao = dao;
	}

	@Override
	public SupplierOrder getSupplierOrderInfo(String orderId) {
		SupplierOrder order = dao.getSupplierOrder(orderId);
		if (order == null) {
			log.warn("在数据库中未找到指定的采购单  id：" + orderId);
		}
		return order;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SupplierOrder> getSupplierOrderList(SupplierCondition condition, PageInfo pageInfo) {
		List results = dao.getPageData(condition, pageInfo);
		if (results == null || results.size() == 0) {
			log.warn("在数据库中未找到采购单数据");
		}
		return results;
	}

	@Override
	public boolean removeSupplierOrder(String orderId) {
		dao.removeSupplierOrder(orderId);
		return true;
	}

	@Override
	public void saveSupplierOrder(SupplierOrder order) {
		if (null == order.getId() || "".equals(order.getId())) {
			String orderId = ListUtil.SUPPLIER_ORDER_ID_PRE + DateUtils.dateToString("yyyyMM");
			int maxId = dao.getMaxOrderId(orderId);
			String newOrderId = orderId + String.format("%04d", maxId + 1);
			log.debug("生成的采购订单编号：" + newOrderId);
			order.setId(newOrderId);
			order.setStatus(SupplierOrder.ORDER_STATES_CREATED);
		}
		order.setUpdateDate(DateUtils.now());
		dao.saveSupplierOrder(order);
	}
	
	/**
	 * 手动结束采购单
	 * @return
	 * @throws Exception
	 */
	public void finishSupplierOrder(String orderId) {
		SupplierOrder order = dao.getSupplierOrder(orderId);
		order.setUpdateDate(DateUtils.now());
		order.setStatus(SupplierOrder.ORDER_STATES_CUSTOM_FINISH);
		dao.saveSupplierOrder(order);
	}

}
